<template>
  <view v-if="utoolsData">
    <!-- <view v-if="utoolsData"  > -->
    <block v-if="showUtoolsData">
      <utools-parse id="utools-parse" page="category"  @setPanel="setPanel"
        :utools-data="utoolsData" @onAddCart="onAddCart"></utools-parse>
    </block>
  </view>
</template>

<script>
  import api from '@/api/api';
  import {
    SEL_CLASS_CODE,
    SEL_ACTIVE_CODE,
    SYSTEM_INFO,
    USER_INFO,
    CUSTOMER_INFO,
    CUSTOMER_HOTFIX,
    CART_KEY,
    MERCHANT_INFO,
    USER_SPECICAL_INFO
  } from '@/utils/constant';
  export default {
    data() {
      return {
        utoolsData: null,
        utoolsClassGoodsLists: null,
        showUtoolsData: false
      };
    },
    async onLoad(option) {
      this.utoolsData = await this.getHomeUtoolsData(option);
      //商品
      let uLists = await this.getCateGoods(this.utoolsData.classId);
      this.utoolsClassGoodsLists = uLists;
      this.showUtoolsData = true;
    },
    methods: {
      async getHomeUtoolsData(option) {
        let optUtid;
        if(option?.scene){
         optUtid = decodeURIComponent(option?.scene)
        }
        let json;
        if ( !!option?.utid) {
          json = await api.getUtoolsJsonP({
            utoolsId: option?.utid,
            type: 'home'
          });
        }else if(!!optUtid){
          json = await api.getUtoolsJsonP({
            utoolsId: optUtid.split('=')[1],
            type: 'home'
          });
        }else {
          json = await api.getUtoolsJson({
            type: option?.uttype || "tipPage"
          });
        }
        return json.success && json?.data ? JSON.parse(json.data) : null;
      },
      /**
       * 查询首页商品分类列表
       * @param {Object} class_id
       * @param {Object} is_sort
       */
      async getCateGoods(class_id, is_sort) {
        try {
          //获取商品
          let merchantInfo = uni.getStorageSync(MERCHANT_INFO)
          let customerInfo = uni.getStorageSync(CUSTOMER_INFO);
          let res = await this.$commonFunction.doSearchGoods(class_id, '', 1, 200, null, '', is_sort, '', '', '', '',
            true)
          let cateProductList = res.data.content; // 商品列表
          //sku实时库存查询
          let skuCodeList = [],
            goodsQ = [];
          for (let i = 0; i < cateProductList.length; i++) {
            skuCodeList = skuCodeList.concat(cateProductList[i].skuCodes)
          }

          if (skuCodeList.length) {
            skuCodeList = await this.setSkuCodeList(skuCodeList)
            for (let i = 0; i < skuCodeList.length; i++) {
              let reset = await this.getAvailableBatchQty(customerInfo, merchantInfo, skuCodeList[i]);
              goodsQ = reset.length ? goodsQ.concat(reset) : goodsQ
            }
          }
          let list = [];
          cateProductList = cateProductList.map(async item => {
            let res = await this.$commonFunction.priceRulesDeal(item.strategies, item.itemmCode)
            if (goodsQ && goodsQ.length) {
              for (let i = 0; i < goodsQ.length; i++) {
                if (item.skuCodes.indexOf(goodsQ[i].skuCode) !== -1 && goodsQ[i].availableQty > 0) {
                  item.frontQty += goodsQ[i].availableQty
                }
              }
            }
            if (res.price !== 0) {
              if (item.itemCode == res.itemCode) {
                item.price = res.price
              }
            }
            if (res.rulesArr.length > 0) {
              if (item.itemCode == res.itemCode) {
                item.rulesArr = res.rulesArr
              }
            }
            // var isForwardpurchaseGoods = false;
            // let  customPromotionTags = item['promotionTagList']?.map(ite=>{
            // 	if (ite.promotionType == 'custom_tag') {
            // 	  customPromotionTags.push(tagItem);
            // 	}

            // 	if (tagItem.promotionType == 'forward_purchase') {
            // 	  isForwardpurchaseGoods = true;
            // 	}
            // 	return ite.promotionType == 'custom_tag'? ite : null
            // })
            list.push(item)
            return item
          })
          return list
        } catch (err) {
          console.log("###### home-getCateGoods-error:", err)
          return null
        }
      },
      async setSkuCodeList(skuCodeList) {
        if (skuCodeList.length < 21) {
          return [skuCodeList]
        } else {
          const result = skuCodeList.flatMap((value, index, array) => {
            if (index % 20 === 0) {
              return [array.slice(index, index + 20)];
            }
            return [];
          });
          return result
        }
      },
      /**
       * 查询有效库存
       * @param {Object} customerInfo
       * @param {Object} merchantInfo
       * @param {Object} skuCodeList
       */
      async getAvailableBatchQty(customerInfo, merchantInfo, skuCodeList) {
        let reset = await api.getAvailableBatchQty({
          method: "POST",
          header: {
            jwt: customerInfo.jwt,
            'content-type': 'application/json'
          },
          query: skuCodeList
          // query: JSON.stringify(skuCodeList)
        }, merchantInfo.cloudMerchantId);
        if (reset.msg == "SUCCESS" && reset?.data?.length) {
          return reset.data.filter(item => item.availableQty > 0)
        } else {
          return []
        }
      },
    }
  }
</script>

<style lang="less">

</style>
